package _2获取WebContext下的文件的磁盘路径;

import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/TestServlet2")
public class TestServlet2 extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		
		
		// ServletContext功能2 
		
		// 1. 得到ServletContext对象
		ServletContext sc = getServletContext();
		
		
		// 2. 得到文件的路径
		String filePath = sc.getRealPath("/WEB-INF/code.txt");
		pw.print("文件在服务器上路径:"+filePath);
		
		
		// 3. 读取文件内容
		Reader r = new FileReader(filePath);
		char[] buf = new char[1024];
		int len = r.read(buf);
		String content = new String(buf,0,len);
		pw.print("<br>文件内容:<br>"+content);
		
		
		
		
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}